/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.yy.bugzillahelp.tool;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.*;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.JTable;
import javax.swing.table.TableCellEditor;

/**
 *
 * @author zyy
 */
public class DataTool {

    private static final Logger logger = Logger.getLogger(DataTool.class.getName());
    public static String PATTERN_DATE_DAY = "yyyy-MM-dd";
    public static String PATTERN_DATE_MONTH = "yyyy-MM";
    public static String PATTERN_DATE_YEAR = "yyyy";
    private static Pattern IS_NUMBER_PATTERN = Pattern.compile("^-?([0-9]+)(\\.[0-9]+)?$");

    /**
     * Set number which such as .3 to 0.3 correctly. 06/23/2011.
     */
    public static String correctNumber(String value) {
        if (value != null && !value.trim().equals("")) {
            int index = value.indexOf(".");

            if (index == 0) {
                String isNumber = "0" + value;
                if (DataTool.isNumber(isNumber)) {
                    value = isNumber;
                }
            }
        }
        return value;
    }

    public static boolean checkDouble(String value) {
        Pattern pattern = Pattern.compile("^[0-9]*\\.?[0-9]*$");
        Matcher matcher = pattern.matcher(value);
        boolean matches = matcher.matches();
        if (matches) {
            try {
                double a = Double.valueOf(value);
                return true;
            } catch (RuntimeException e) {
                return false;
            }
        } else {
            return false;
        }
    }

    public static double convertNaNToZero(double d) {
        if (Double.isNaN(d)) {
            return 0.0;
        } else {
            return d;
        }
    }

    public static String[] split(String array) {
        ArrayList<String> list = new ArrayList<String>();
        String temp;
        String source = array;
        int indexx = source.indexOf("/");

        while (true) {
            if (indexx == -1) {
                temp = source;
                list.add(temp);
                break;
            } else {
                temp = source.substring(0, indexx);
                if (indexx != source.length() - 1) {
                    source = source.substring(indexx + 1);
                } else {
                    source = "";
                }
                list.add(temp);
                indexx = source.indexOf("/");
            }
        }

        return list.toArray(new String[0]);
    }

    public static void cancelTableEditing(JTable jTable) {
        TableCellEditor cellEditor = jTable.getCellEditor();
        if (cellEditor != null) {
            cellEditor.stopCellEditing();
        }
    }

    public static String nullToEmpty(Object str) {
        if (str == null) {
            return "";
        } else {
            return str.toString().trim();
        }
    }

    public static Double StringToDouble(String value) {
        value = nullToEmpty(value);
        value = value.trim();
        Double d;
        try {
            d = Double.valueOf(value);
        } catch (RuntimeException e) {
            d = Double.NaN;
        }
        return d;
    }

    public static String DoubleToString(Double value) {
        if (Double.isNaN(value) || Double.isInfinite(value)) {
            return "";
        } else {
            return nullToEmpty(value);
        }
    }

    public static Double checkDouble(Double value) {
        if (Double.isNaN(value)) {
            return 0.0;
        }
        return value;
    }

    public static String parseDateToString(Calendar calendar, String pattern) {
        SimpleDateFormat dateFormat = new SimpleDateFormat(pattern);
        return dateFormat.format(calendar.getTime());
    }

    public static String convertNAToNULL(String value) {
        if (value != null) {
            if (value.equalsIgnoreCase("na") || value.equals("")) {
                value = null;
            }
        }
        return value;
    }

    // Change codeValue to value. 01/10/2011.
    public static String changeCodeValueToValue(String codeValue) {
        String value = "";

        if (codeValue != null) {
            int index1 = codeValue.indexOf("/");
            int index2 = codeValue.indexOf(":");
            if (codeValue.startsWith("http") || codeValue.startsWith("HTTP")) {
                value = codeValue;
            } else if (index1 > -1) {
                String[] str1 = codeValue.split("/");
                for (int i = 0; i < str1.length; i++) {
                    int innerIndex = str1[i].indexOf(":");
                    if (innerIndex > -1) {
                        value += str1[i].substring(innerIndex + 1) + "/";
                    } else {
                        value += str1[i] + "/";
                    }
                }
                value = value.substring(0, value.length() - 1);
            } else if (index2 > -1) {
                value = codeValue.substring(index2 + 1);
            } else {
                value = codeValue;
            }
        }
        return value;
    }

    public static String changeCodeValueToCode(String codeValue) {
        String value = "";

        if (codeValue != null) {
            int index1 = codeValue.indexOf("/");
            int index2 = codeValue.indexOf(":");
            if (codeValue.startsWith("http") || codeValue.startsWith("HTTP")) {
                value = codeValue;
            } else if (index1 > -1) {
                String[] str1 = codeValue.split("/");
                for (int i = 0; i < str1.length; i++) {
                    int innerIndex = str1[i].indexOf(":");
                    if (innerIndex > -1) {
                        value += str1[i].substring(0, innerIndex) + "/";
                    } else {
                        value += str1[i] + "/";
                    }
                }
                value = value.substring(0, value.length() - 1);
            } else if (index2 > -1) {
                value = codeValue.substring(0, index2);
            } else {
                value = codeValue;
            }
        }
        return value;
    }

    public static void changeCodeToValue(HashMap<String, String> map) {
        Iterator<String> it = map.keySet().iterator();
        while (it.hasNext()) {
            String columnName = it.next();
            String value = map.get(columnName);
            if (value != null) {
                value = value.trim();
            }
            if (columnName.equalsIgnoreCase("CUR_FLD_STS") || columnName.equalsIgnoreCase("CUR_RVR_STS") || columnName.equalsIgnoreCase("CUR_PROD_STAGE") || columnName.equals("BALLY_BASIN_TYPE") || columnName.equals("KLEMME_BASIN_TYPE") || columnName.equals("SEAL_CLSS") || columnName.equals("DATA_Q")) {
                map.put(columnName, value.substring(value.indexOf(":") + 1));
            }
            if (columnName.indexOf("TRAP_TIME") >= 0 || columnName.indexOf("SDBD_TYPE") >= 0 || columnName.equals("PROD_STAGES") || columnName.indexOf("ENV_TYPE") > 0 || columnName.indexOf("TRAP_MECH") > 0 || columnName.equalsIgnoreCase("MAIN_DEP_SYS") || columnName.equalsIgnoreCase("SEC_DEP_SYS") || columnName.equals("SRC_ROCK_PERIOD") || columnName.equals("SEAL_PERIOD") || columnName.equals("PROD_RVR_PERIOD") || columnName.equals("HC_EXP_TIME_PERIOD") || columnName.equals("SRC_ROCK_EPOCH") || columnName.equals("SEAL_EPOCH") || columnName.equals("PROD_RVR_EPOCH") || columnName.equals("HC_EXP_TIME_EPOCH") || columnName.equals("SRC_ROCK_AGE") || columnName.equals("SEAL_AGE") || columnName.equals("PROD_RVR_AGE") || columnName.endsWith("SEC_RCVR_METHOD") || columnName.startsWith("EOR_MTHD_THERM") || columnName.startsWith("EOR_MTHD_CHEM") || columnName.startsWith("EOR_MTHD_MSBL") || columnName.startsWith("EOR_MTHD_OTR") || columnName.startsWith("OTR_IMP_RCVR_MTHD_DRL") || columnName.startsWith("OTR_IMP_RCVR_MTHD_STML") || columnName.startsWith("OTR_IMP_RCVR_MTHD_WTR_INJ_OPT") || columnName.startsWith("OTR_IMP_RCVR_MTHD_ART_LIFT") || columnName.startsWith("OTR_IMP_RCVR_MTHD_SND_CNTRL") || columnName.startsWith("OTR_IMP_RCVR_MTHD_RVR_MNG") || columnName.startsWith("SEC_RCVR_IMPL_SCL_PLT") || columnName.startsWith("SEC_RCVR_IMPL_SCL_PRT") || columnName.startsWith("SEC_RCVR_IMPL_SCL_FLD") || columnName.startsWith("REM_OIL_CHRCT_TECH") || columnName.endsWith("PERF_TYPE") || columnName.startsWith("CUR_WELL_PAT") || columnName.startsWith("COMPL_TYPE_VERT") || columnName.startsWith("COMPL_TYPE_MLT_LTR") || columnName.startsWith("COMPL_TYPE_HOR") || columnName.startsWith("COMPL_TYPE_ERD") || columnName.endsWith("EOR_METHOD") || columnName.endsWith("OTR_IMP_RCVR_METHOD") || columnName.endsWith("EOR_MTHD_IMPL_SCL_PLT") || columnName.endsWith("EOR_MTHD_IMPL_SCL_PRT") || columnName.endsWith("EOR_MTHD_IMPL_SCL_FLD") || columnName.endsWith("DRV_MECH") || columnName.endsWith("GRAIN_SIZE") || columnName.equalsIgnoreCase("STATE") || columnName.equalsIgnoreCase("PROD_FACIL") || columnName.equalsIgnoreCase("FM_DMG_TYPE") || columnName.equalsIgnoreCase("CSNG_DMG_CAUSE") || columnName.equalsIgnoreCase("CSNG_DMG_REMD") || columnName.equalsIgnoreCase("FRAC_RVR_TYPE") || columnName.equalsIgnoreCase("RSC_CAT") || columnName.equalsIgnoreCase("RSC_UNC") || columnName.equalsIgnoreCase("RSC_MAT") || columnName.endsWith("HC_TYPE") || columnName.endsWith("FLW_RSTRCT")) {
                String values[] = value.split("/");
                String temp = "";
                for (int i = 0; i < values.length; i++) {
                    String string = values[i];
                    temp = temp + string.substring(string.indexOf(":") + 1) + "/";
                }
                if (!temp.equals("")) {
                    map.put(columnName, temp.substring(0, temp.length() - 1));
                }
            }
        }
    }

    // <editor-fold defaultstate="" desc="convert html">
    // Array convert to ArrayList. 11/22/2010.
    public static ArrayList arrayToArrayList(Object[] obj) {
        ArrayList al = new ArrayList();
        for (int i = 0; i < obj.length; i++) {
            al.add(obj[i]);
        }
        return al;
    }

    // Return now date according to the specified format. 10/14/2010.
    public static String DateFormat(String type) {
        String dateTimeFormat = "yyyy-MM-dd";
        if (type.equals("dateTime")) {
            dateTimeFormat = "yyyy-MM-dd kk:mm:ss";
        }
        SimpleDateFormat dateFormat = new SimpleDateFormat(dateTimeFormat);
        Date date = new Date();
        String nowDate = dateFormat.format(date);
        nowDate = nowDate.replaceAll(" 24:", " 00:");
        return nowDate;
    }

    public static String clearBrTag(String value) {
        if (value == null) {
            return "";
        }

        int index = value.lastIndexOf("<br />");
        if (index > -1 && index == value.length() - 6) {
            value = value.substring(0, value.length() - 6);
        }
        return value;
    }

    // Clear html tag in document of report and Excel. 04/08/2011.
    public static String clearHTMLTagExceptATag(String htmlStr) {
        String regEx_html = "</?[b-zB-Z]+[^>]*>";

        Pattern p_html = Pattern.compile(regEx_html, Pattern.CASE_INSENSITIVE);
        Matcher m_html = p_html.matcher(htmlStr);
        htmlStr = m_html.replaceAll(""); // Clear html tag
        htmlStr = replaceHTMLCharacter(htmlStr);

        return htmlStr;
    }

    // Clear html tag in document of report and Excel. 04/08/2011.
    public static String clearHTMLTag(String htmlStr) {
        String regEx_html = "</?[a-zA-Z]+[^>]*>";

        Pattern p_html = Pattern.compile(regEx_html, Pattern.CASE_INSENSITIVE);
        Matcher m_html = p_html.matcher(htmlStr);
        htmlStr = m_html.replaceAll(""); // Clear html tag
        htmlStr = replaceHTMLCharacter(htmlStr);

        return htmlStr;
    }

    // Replace the html special character in document of report and Excel. 04/13/2011.
    public static String replaceHTMLCharacter(String htmlStr) {
        // English
        htmlStr = htmlStr.replaceAll("&nbsp;", " ");
        htmlStr = htmlStr.replaceAll("&amp;", "&");
        htmlStr = htmlStr.replaceAll("&quot;", "\"");
        htmlStr = htmlStr.replaceAll("&lt;", "<");
        htmlStr = htmlStr.replaceAll("&gt;", ">");

        // Chinese
        htmlStr = htmlStr.replaceAll("&hellip;", "…");
        htmlStr = htmlStr.replaceAll("&times;", "×");
        htmlStr = htmlStr.replaceAll("&mdash;", "—");
        htmlStr = htmlStr.replaceAll("&ldquo;", "“");
        htmlStr = htmlStr.replaceAll("&rdquo;", "”");
        htmlStr = htmlStr.replaceAll("&lsquo;", "‘");
        htmlStr = htmlStr.replaceAll("&rsquo;", "’");
        htmlStr = htmlStr.replaceAll("&middot;", "·");

        return htmlStr;
    }

    public static String getResourceId(String fldId, String rvrCode, boolean isReservoir) {
        String resource_id;
        if (isReservoir) {
            resource_id = rvrCode;
        } else {
            resource_id = fldId;
        }
        return resource_id;
    }
    // </editor-fold>

    public static String getTextFromCodeValue(String codeValue) {
        String text = "";
        if (codeValue != null && !codeValue.trim().equals("")) {
            String[] split = codeValue.split("/");
            for (String string : split) {
                if (!string.trim().equals("")) {
                    int index = string.indexOf(":");
                    if (index > -1) {
                        text += "/" + string.substring(index + 1);
                    } else {
                        text += "/" + string;
                    }
                }
            }
            if (text.startsWith("/")) {
                text = text.substring(1);
            }
        }
        return text;
    }

    public static boolean isEmpty(String value) {
        if (value == null || value.trim().equals("")) {
            return true;
        } else {
            return false;
        }
    }

    public static boolean isEmpty(HashMap map) {
        if (map == null || map.isEmpty()) {
            return true;
        } else {
            return false;
        }
    }

    public static boolean isEmpty(List list) {
        if (list == null || list.isEmpty()) {
            return true;
        } else {
            return false;
        }
    }

    public static boolean isInteger(String value) {
        if (value == null || value.trim().equals("")) {
            return false;
        }
        try {
            Integer.parseInt(value);
        } catch (Exception e) {
            return false;
        }
        return true;
    }

    public static boolean isDouble(String value) {
        if (value == null || value.trim().equals("")) {
            return false;
        }
        try {
            Double.parseDouble(value);
        } catch (Exception e) {
            return false;
        }
        return true;
    }

    public static boolean isNumber(String number) {
        if (number == null || number.trim().contains(" ")) {
            return false;
        }

        Matcher matcher = IS_NUMBER_PATTERN.matcher(number);
        return matcher.matches();
    }

    public static int getFirstNumber(String string) {
        int number = -1;

        if (string != null) {
            Pattern compiler = Pattern.compile("(\\d+)");
            Matcher matcher = compiler.matcher(string);
            if (matcher.find()) {
                String group = matcher.group(1);
                if (group != null
                        && group.length() <= 4
                        && isNumber(group)) {
                    number = Integer.parseInt(group);
                }
            }
        }

        return number;
    }

    /**
     * judge is a string's each char is a digital
     */
    public static boolean isAllDigital(String value) {
        if (DataTool.isEmpty(value)) {
            return false;
        }

        Pattern p = Pattern.compile("^\\d+$");
        Matcher matcher = p.matcher(value);
        return matcher.matches();
    }

    public static boolean isCDDMColumn(String str) {
        Pattern pattern = Pattern.compile("[0-9]+");
        return pattern.matcher(str).matches();
    }

    public static String getPureUserName(String userName) {
        if (userName != null && !userName.trim().equals("")) {
            int index = userName.indexOf(":");
            if (index > 0) {
                userName = userName.substring(0, index);
            }
        }
        return userName;
    }

    public static String removeSpace(String str) {
        if (str == null) {
            return null;
        }

        str = str.trim();
        str = str.replaceAll("\\s+", " ");

        return str;
    }

    /**
     * 将列表中的字符串信息进行组合，中间使用','隔开。主要用于将一个列名列表组合成SQL的Select部分。
     *
     * @param columnNames
     * @return
     */
    public static String combineStrings(ArrayList<String> columnNames) {
        StringBuilder sb = new StringBuilder();
        for (String string : columnNames) {
            sb.append(string).append(",");
        }
        if (sb.length() > 0) {
            sb.deleteCharAt(sb.length() - 1);
        }
        return sb.toString();
    }

    /**
     * 将列表中的字符串信息进行组合，中间使用逗号(,)隔开，同时每个项用单引号(')围绕。主要用于将一个列名列表组合成SQL的Select部分。
     *
     * @param columnNames
     * @return
     */
    public static String combineStrings2(ArrayList<String> columnNames) {
        StringBuilder sb = new StringBuilder("'");
        for (String string : columnNames) {
            sb.append(string).append("','");
        }

        if (sb.length() > 1) {
            sb.deleteCharAt(sb.length() - 1);
            sb.deleteCharAt(sb.length() - 1);
            return sb.toString();
        } else {
            return "";
        }
    }

    public static String getAllColName(String colDesc) {
        String desc = "";

        if (DataTool.isEmpty(colDesc)) {
            return desc;
        }

        //retrieve all words between first " " and first ":"
        if (colDesc.indexOf(" ") != -1 && colDesc.indexOf(":") != -1) {
            desc = colDesc.substring(colDesc.indexOf(" "), colDesc.indexOf(":"));
        }
        return desc;
    }

    /**
     * 从String数组中查找指定的String
     *
     * @param strs
     * @param value
     * @return 如找到，则返回其索引；否则返回-1
     */
    public static int searchItem(String[] strs, String value) {
        if (value == null || strs == null) {
            return -1;
        }

        for (int i = 0; i < strs.length; i++) {
            if (value.equals(strs[i])) {
                return i;
            }
        }
        return -1;

    }

    public static String getExceptionDetails(Exception e) {
        StringWriter stringWriter = new StringWriter();
        e.printStackTrace(new PrintWriter(stringWriter));
        return stringWriter.toString();
    }
}
